package com.daoyintech.services;

import com.daoyintech.entity.bean.Event;
import com.daoyintech.entity.bean.RedEnvelope;
import com.daoyintech.entity.bean.WeixinTicket;
import com.daoyintech.entity.weixin.request.WeixinEventTicketRequest;
import com.daoyintech.entity.weixin.request.WeixinHongBaoRequest;
import com.daoyintech.entity.weixin.response.WeixinEventTicketResponse;
import com.daoyintech.entity.weixin.response.WxXmlRedEnvelope;
import com.daoyintech.repository.EventRepository;
import com.daoyintech.repository.RedEnvelopeRepository;
import com.daoyintech.utils.HongBaoUtil;
import com.daoyintech.utils.MapUtil;
import com.daoyintech.utils.SignatureUtil;
import com.daoyintech.utils.WebUtils;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by xuzhaolin on 15/12/29.
 */
@Service
public class RedEnvelopeService implements EnvironmentAware{

    private static final String createRedEnvelopeUrl = "https://api.mch.weixin.qq.com/mmpaymkttransfers/hbpreorder";
    private static final String setBucketUrl = "https://api.weixin.qq.com/shakearound/lottery/setprizebucket?access_token=";
    private static final String success_flag = "SUCCESS";


    @Autowired
    private RedEnvelopeRepository redEnvelopeRepository;


    @Autowired
    private EventRepository eventRepository;


    @Autowired
    private WxMpService wxMpService;

    @Autowired
    private WeixinPayService weixinPayService;

    private RelaxedPropertyResolver propertyResolver;
    private String mch_id;
    private String wxappid;
    private String paykey;


    @Override
    public void setEnvironment(Environment environment) {
        this.propertyResolver = new RelaxedPropertyResolver(environment,"weixin.");
        this.mch_id  = propertyResolver.getProperty("store_id");
        this.wxappid = propertyResolver.getProperty("appid");
        this.paykey  = propertyResolver.getProperty("pay_key");
    }



    public List<RedEnvelope> findAll(){
        return (List<RedEnvelope>) redEnvelopeRepository.findAll();
    }

    public RedEnvelope create(String money) {
       return createRedEnvelope(createWeixinHongBao(money));
    }


    public boolean bindRedEnvelopeAndEvent(long event_id,int number,long red_envelope_id) {
       WeixinEventTicketResponse response =  bindWeixinTicketAndEvent(event_id,number,red_envelope_id);
        if(response.getErrcode() == 0){
            return true;
        }else{
            return false;
        }
    }

    public void deleteAll(){
        redEnvelopeRepository.deleteAll();
    }


// 内部方法
    private WxXmlRedEnvelope createWeixinHongBao(String money){
        WeixinHongBaoRequest hongBao = new WeixinHongBaoRequest();
        hongBao.setMch_id(this.mch_id);
        hongBao.setWxappid(this.wxappid);

//            设置字段
        hongBao.setMch_billno(setOrderNumber());
        hongBao.setNonce_str(HongBaoUtil.getNonceStr());
        hongBao.setTotal_amount(money);

//        设置固定值
        hongBao.setHb_type("NORMAL");
        hongBao.setTotal_num("1");
        hongBao.setAmt_type("ALL_RAND");
        hongBao.setAuth_mchid("1000052601");
        hongBao.setAuth_appid("wxbf42bd79c4391863");
        hongBao.setRisk_cntl("NORMAL");

//        设置显示内容
        hongBao.setSend_name("中信银行成都分行");
        hongBao.setWishing("祝您新年快乐");
        hongBao.setAct_name("中信银行成都分行");
        hongBao.setRemark("祝您新年快乐");


        Map<String,String> params =  MapUtil.objectToMap(hongBao,"sign");
        String key = SignatureUtil.generateSign(params,this.paykey);
        hongBao.setSign(key);

        try {
            RestTemplate restTemplate = new RestTemplate(weixinPayService.wxPayHttpClient());
            String requestBody = new String(hongBao.toXml().getBytes(),"ISO8859-1");
            String result = restTemplate.postForObject(createRedEnvelopeUrl,requestBody,String.class);
            WxXmlRedEnvelope response = WxXmlRedEnvelope.fromXml(result);
            return response;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }


    private RedEnvelope createRedEnvelope(WxXmlRedEnvelope response) {

        if(response.getResult_code().equals(success_flag) && response.getReturn_code().equals(success_flag)){
            RedEnvelope redEnvelope = new RedEnvelope();
            redEnvelope.setOrderNumber(response.getMch_billno());
            redEnvelope.setTicket(response.getSp_ticket());
            redEnvelopeRepository.save(redEnvelope);
            return redEnvelope;
        }


        return null;
    }


    private WeixinEventTicketResponse bindWeixinTicketAndEvent(long event_id,int number,long red_envelope_id) {
        Event event = eventRepository.findOne(event_id);
        RedEnvelope redEnvelope = redEnvelopeRepository.findOne(red_envelope_id);
        List<WeixinTicket> tickets = new ArrayList<WeixinTicket>();
//        for(int i = 0;i< number;i++){
//            WeixinTicket ticket = new WeixinTicket();
//            ticket.setTicket(redEnvelope.getTicket());
//            tickets.add(ticket);
//        }
        List<RedEnvelope> redEnvelopes = (List<RedEnvelope>) redEnvelopeRepository.findAll();
        for(RedEnvelope redEnvelope1: redEnvelopes){
            WeixinTicket ticket = new WeixinTicket();
            ticket.setTicket(redEnvelope1.getTicket());
            tickets.add(ticket);
            WeixinEventTicketRequest request = new WeixinEventTicketRequest();
            request.setLottery_id(event.getLottery_id());
            request.setMchid(this.mch_id);
            request.setSponsor_appid(this.wxappid);
            request.setPrize_info_list(tickets);
            String accessToken = null;
            try {
                accessToken = wxMpService.getAccessToken();
            } catch (WxErrorException e) {
                e.printStackTrace();
                return null;
            }
            String url = setBucketUrl+accessToken;
            RestTemplate restTemplate = new RestTemplate();
            String response =  restTemplate.postForObject(url,request,String.class);
            System.out.println(response);

        }

//        WeixinEventTicketRequest request = new WeixinEventTicketRequest();
//        request.setLottery_id(event.getLottery_id());
//        request.setMchid(this.mch_id);
//        request.setSponsor_appid(this.wxappid);
//        request.setPrize_info_list(tickets);
//        String accessToken = null;
//        try {
//            accessToken = wxMpService.getAccessToken();
//        } catch (WxErrorException e) {
//            e.printStackTrace();
//            return null;
//        }
//        String url = setBucketUrl+accessToken;
//        RestTemplate restTemplate = new RestTemplate();
//        String response =  restTemplate.postForObject(url,request,String.class);
        return null;
    }



    private String setOrderNumber(){
        RedEnvelope redEnvelope = null;
        String orderNumber = null;
        do{
            long randomNumber = HongBaoUtil.getRandomOrderNumber();
            orderNumber = this.mch_id+ WebUtils.getTodayDate()+String.valueOf(randomNumber);
            redEnvelope = redEnvelopeRepository.findByOrderNumber(orderNumber);

        }while (redEnvelope != null);
        return orderNumber;
    }

}
